<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <!-- 结算账户 新增/编辑 -->
  <view class="Mall4j page-allinpay-store-account">
    <view class="uni-forms-box">
      <uni-forms
        ref="accountFormRef"
        :model-value="accounts"
        :rules="rules"
        validate-trigger="submit"
      >
        <!-- 账户类型 -->
        <view class="setting-info-item">
          <uni-forms-item key="bankCardPro">
            <view class="title">
              <text class="star">
                *
              </text>
              <text class="txt">
                账户类型
              </text>
            </view>
            <view class="radio-con">
              <radio-group @change="onChangeAccountType">
                <radio
                  v-if="!(baseInfoForm.companyInfoProcessStatus === 0 || baseInfoForm.companyInfoProcessStatus === 3)"
                  style="transform:scale(0.8);"
                  value="0"
                  color="#082BA6"
                  :disabled="!(legalCardNumber<1)"
                  :checked="accounts.bankCardPro === 0"
                >
                  <text class="radio-txt">
                    法人账户
                  </text>
                </radio>
                <radio
                  style="transform:scale(0.8)"
                  value="1"
                  color="#082BA6"
                  :disabled="!(cardNumber<10)"
                  :checked="accounts.bankCardPro === 1"
                >
                  <text class="radio-txt">
                    对公账户
                  </text>
                </radio>
              </radio-group>
            </view>
          </uni-forms-item>
        </view>
        <!-- 银行名称 -->
        <view
          v-if="accounts.bankCardPro===1"
          class="setting-info-item"
        >
          <uni-forms-item
            key="parentBankName"
            name="parentBankName"
          >
            <view class="title">
              <text class="star">
                *
              </text>
              <text class="txt">
                银行名称
              </text>
            </view>
            <view class="bank-select-plus">
              <jp-select-plus
                v-model="selectBank"
                show-name="bankName"
                keys="bankId"
                :is-line="false"
                color="#004EA2"
                placeholder="请选择"
                is-search
                :list="bankList"
                @to-confirm="onChangeBank"
              />
            </view>
          </uni-forms-item>
        </view>

        <!-- 开户行 -->
        <view
          v-if="accounts.bankCardPro===1"
          class="setting-info-item"
        >
          <uni-forms-item
            key="bankName"
            name="bankName"
          >
            <view class="title">
              <text class="star">
                *
              </text>
              <text class="txt">
                开户支行名称
              </text>
            </view>
            <view class="input-box">
              <uni-easyinput
                v-model="accounts.bankName"
                placeholder="如：“中国工商银行股份有限公司北京樱桃园支行”"
                maxlength="20"
                @blur="onCheckInput('bankName')"
              />
            </view>
          </uni-forms-item>
        </view>

        <!-- 账户 -->
        <view
          v-if="accounts.bankCardPro===1"
          class="setting-info-item"
        >
          <uni-forms-item
            key="accountNo"
            name="accountNo"
          >
            <view class="title">
              <text class="star">
                *
              </text>
              <text class="txt">
                请输入企业对公账户
              </text>
            </view>
            <view
              name="accountNo"
              class="input-box"
            >
              <uni-easyinput
                v-model="accounts.accountNo"
                placeholder="请输入账户名"
                maxlength="19"
                @blur="onCheckInput('accountNo')"
              />
            </view>
          </uni-forms-item>
        </view>

        <!-- 支付行号 -->
        <view
          v-if="accounts.bankCardPro===1"
          class="setting-info-item"
        >
          <uni-forms-item
            key="unionBank"
            name="unionBank"
          >
            <view class="title">
              <text class="star">
                *
              </text>
              <text class="txt">
                支付行号
              </text>
            </view>
            <view class="input-box">
              <uni-easyinput
                v-model="accounts.unionBank"
                type="number"
                placeholder="请输入支付行号"
                maxlength="12"
                @blur="onCheckInput('unionBank')"
              />
            </view>
          </uni-forms-item>
        </view>

        <!-- 法人账户开始 -->
        <view
          v-if="accounts.bankCardPro===0"
          class="setting-info-item"
        >
          <uni-forms-item
            key="cardNo"
            name="cardNo"
          >
            <view class="title">
              <text class="star">
                *
              </text>
              <text class="txt">
                账户
              </text>
            </view>
            <view class="input-box">
              <uni-easyinput
                v-model="accounts.cardNo"
                placeholder="请输入银行卡号"
                maxlength="19"
                @blur="onCheckInput('cardNo')"
              />
            </view>
          </uni-forms-item>
        </view>
        <view
          v-if="accounts.bankCardPro===0"
          class="setting-info-item"
        >
          <uni-forms-item
            key="identityNo"
            name="identityNo"
          >
            <view class="title">
              <text class="star">
                *
              </text>
              <text class="txt">
                身份证
              </text>
            </view>
            <view class="input-box">
              <uni-easyinput
                v-model="accounts.identityNo"
                placeholder="请输入身份证号"
                maxlength="20"
                @blur="onCheckInput('identityNo')"
              />
            </view>
          </uni-forms-item>
        </view>
        <view
          v-if="accounts.bankCardPro===0"
          class="setting-info-item"
        >
          <uni-forms-item
            key="mobile"
            name="mobile"
          >
            <view class="title">
              <text class="star">
                *
              </text>
              <text class="txt">
                手机号
              </text>
            </view>
            <view class="input-box">
              <uni-easyinput
                v-model="accounts.mobile"
                placeholder=" 请输入银行预存手机号"
                maxlength="11"
                @blur="onCheckInput('mobile')"
              />
            </view>
          </uni-forms-item>
        </view>
      </uni-forms>
    </view>
    <!-- 添加账户 -->
    <view class="account-footer">
      <button
        type="default"
        hover-class="none"
        @tap="onSubmit()"
      >
        确定
      </button>
    </view>
  </view>
</template>

<!-- eslint-disable n/no-callback-literal -->
<script setup>
import { checkIDCard } from '@/utils/validate'

const selectBank = ref(0)
const rules = ref({
  parentBankName: {
    rules: [
      { required: true, errorMessage: '请选择银行名称' }
    ]
  },
  bankName: {
    rules: [
      { required: true, errorMessage: '请输入银行开户行' },
      {
        validateFunction: (rule, value, data, callback) => {
          if (value.length < 2 || value.length > 20) {
            callback('银行开户行长度在2-20个字符')
            return false
          }
          return true
        }
      }
    ]
  },
  accountNo: {
    rules: [
      { required: true, errorMessage: '企业对公账户不能为空' }
    ]
  },
  unionBank: {
    rules: [
      { required: true, errorMessage: '请输入支付行号' },
      {
        validateFunction: (rule, value, data, callback) => {
          if (value.length < 12 || value.length > 12) {
            callback('请输入12位数字')
            return false
          }
          return true
        }
      }
    ]
  },
  mobile: {
    rules: [
      { required: true, errorMessage: '手机号不能为空' },
      {
        validateFunction: (rule, value, data, callback) => {
          const reg = /^1[0-9]{10}$/
          if (!reg.test(value)) {
            callback('请输入正确的手机号')
            return false
          }
          return true
        }
      }
    ]
  },
  cardNo: {
    rules: [
      { required: true, errorMessage: '请输入账户' },
      {
        validateFunction: (rule, value, data, callback) => {
          const reg = /^([0-9]{1})(\d{12,18})$/
          if (!reg.test(value)) {
            callback('请输入正确的银行卡号')
            return false
          }
          return true
        }
      }
    ]
  },
  identityNo: {
    rules: [
      { required: true, errorMessage: '身份证号码不能为空' },
      {
        validateFunction: (rule, value, data, callback) => {
          if (!value || !checkIDCard(value)) {
            callback('请输入正确的银行卡号')
            return false
          }
          return true
        }
      }
    ]
  }
})

onLoad(() => {
  // 头部导航标题
  uni.setNavigationBarTitle({
    title: '新增账户'
  })
  onGetBankList()
  onGetShopBankCardList()
  onGetShopDetailnfo()
})
/**
 * 获取店铺信息
 */
const baseInfoForm = ref({})// 店铺信息
const onGetShopDetailnfo = () => {
  const params = {
    url: '/shop/shopDetail/info',
    method: 'GET'
  }
  http.request(params).then(({ data }) => {
    baseInfoForm.value = data
  })
}

/**
 * 获取店铺下的账户列表
 */
const legalCardNumber = ref(0)
const cardNumber = ref(0)
// 编辑账户信息
const accounts = reactive({
  parentBankName: '',
  openingBank: '',
  cardNo: '',
  bankCardPro: 1,
  mobile: '', // 银行预存手机号
  unionBank: '', // 支付行号
  accountNo: '', // 企业对公账户
  identityNo: '' // 身份证号
})
const onGetShopBankCardList = () => {
  const params = {
    url: '/shop/shopBankCard/getShopBankCardList',
    method: 'GET'
  }
  uni.showLoading({
    mask: true
  })
  http.request(params).then(({ data }) => {
    if (data && data.length > 0) {
      legalCardNumber.value = data.filter(item => item.bankCardPro === 0).length
      cardNumber.value = data.length - legalCardNumber.value
      accounts.bankCardPro = cardNumber.value < 10 ? 1 : 0
    }
    uni.hideLoading()
  })
}
/**
 * 切换单选
 */
const onChangeAccountType = (val) => {
  accounts.bankCardPro = Number(val.detail.value)
}
/**
 * 检查输入框空格
 */
const onCheckInput = (type) => {
  const reg = /^\s+$/g
  if (type === 'bankName' && reg.test(accounts.bankName)) {
    accounts.bankName = ''
  }
  if (type === 'openingBank' && reg.test(accounts.openingBank)) {
    accounts.openingBank = ''
  }
  if (type === 'recipientName' && reg.test(accounts.recipientName)) {
    accounts.recipientName = ''
  }
  if (type === 'cardNo' && reg.test(accounts.cardNo)) {
    accounts.cardNo = ''
  }
}

/**
 *  添加银行卡信息
 */
let isAddBankCard = false// 是否正在添加银行卡
const onAddShopBankCard = () => {
  if (isAddBankCard) {
    return
  }
  isAddBankCard = true
  let dataForm
  let url
  if (accounts.bankCardPro === 1) {
    // 对公账户
    dataForm = {
      accountNo: accounts.accountNo,
      bankName: accounts.bankName,
      parentBankName: accounts.parentBankName,
      unionBank: accounts.unionBank
    }
    url = '/shop/allinpay/company/bindCompanyAccount'
  } else {
    // 法人账户
    dataForm = {
      cardNo: accounts.cardNo,
      phone: accounts.mobile,
      identityNo: accounts.identityNo
    }
    url = '/shop/allinpay/company/applyBindBankCard'
  }
  const params = {
    url,
    data: dataForm,
    method: 'POST'
  }
  http.request(params).then(() => {
    isAddBankCard = false
    uni.redirectTo({
      url: '/package-settings/pages/store-settings-financial/store-settings-financial'
    })
  }).catch((err) => {
    isAddBankCard = false
    uni.showToast({
      title: err.msg,
      icon: 'none',
      duration: 1500
    })
  })
}

// 重新提交申请
const applySubmit = ref(false) // 是否正在提交申请
const onResubmitApply = () => {
  if (applySubmit.value) {
    return
  }
  applySubmit.value = true
  uni.showLoading()
  http.request({
    url: '/shop/shopBankCard/allinpaySaveAndApplyShop',
    method: 'post',
    data: accounts
  }).then(() => {
    uni.showToast({
      title: '提交申请成功！',
      icon: 'none',
      duration: 1500,
      complete: () => {
        applySubmit.value = false
        uni.hideLoading()
        setTimeout(() => {
          uni.redirectTo({
            url: '/pages/store-settings/store-settings'
          })
        }, 1500)
      }
    })
  })
}

/**
 * 提交表单
 */
const accountFormRef = ref(null)
const onSubmit = () => {
  accountFormRef.value.validate().then(() => {
    if (baseInfoForm.value.companyInfoProcessStatus === 0 || baseInfoForm.value.companyInfoProcessStatus === 3) {
      onResubmitApply()
    } else {
      onAddShopBankCard()
    }
  })
}

const bankList = ref([])
const onGetBankList = () => {
  http.request({
    url: '/publicBank/list',
    method: 'get'
  }).then(({ data }) => {
    bankList.value = data.map((item) => {
      return {
        ...item,
        bankId: item.bankId + ''
      }
    })
  })
}

const onChangeBank = (val) => {
  if (val && val.length > 0) {
    accounts.parentBankName = val[0].bankName
  }
}
</script>
<style lang="scss" scoped>
@use './allinpay-store-account.scss';
</style>
